package com.woniu.crowd.service.impl;

import java.math.BigDecimal;

import cn.hutool.core.lang.Snowflake;
import com.woniu.after.client.RefundsApplyManageClient;
import com.woniu.after.client.param.CrowdRefundsMoneyParam;
import com.woniu.crowd.common.CrowdException;
import com.woniu.crowd.infra.model.*;
import com.woniu.crowd.infra.model.es.CrowdEsModel;
import com.woniu.crowd.service.*;

import java.util.ArrayList;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.crowd.service.form.CreatCrowdOrderForm;
import com.woniu.crowd.service.form.UPdateCrowdForm;
import com.woniu.exception.LXLGException;
import com.woniu.product.client.ProductQueryClient;
import com.woniu.product.client.result.SpuResultInfo;
import com.woniu.util.DateUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class XXLJobServiceImpl {
    private static Logger logger = LoggerFactory.getLogger(XXLJobServiceImpl.class);
    @Resource
    private CrowdfundingProductsService crowdfundingProductsService;

    @Resource
    private CrowdUserReleService crowdUserReleService;

    @Resource
    private CrowdOrderService crowdOrderService;
    @Resource
    private CrowdOrderLogService crowdOrderLogService;
    @Resource
    private ProductQueryClient productQueryClient;

    @Resource
    private ElasticsearchOperations elasticsearchOperations;

    @Resource
    private RefundsApplyManageClient refundsApplyManageClient;

    @Resource
    private Snowflake snowflake;

    @Resource
    private CrowdLogService crowdLogService;

    @XxlJob("testJobHandler")
    public void testJobHandler() throws Exception {
        System.out.println("开始执行定时任务");
        //将日志上传到xxl-job-admin
        XxlJobHelper.log("乐享乐购:众筹统计启动");
        //查询正在进行的全部众筹
        List<CrowdfundingProducts> crowdfundingProductsList = crowdfundingProductsService.list(new QueryWrapper<CrowdfundingProducts>().eq("croed_state", "CREATED"));
        if (crowdfundingProductsList.size() <= 0)
            throw new LXLGException(CrowdException.CROWD_HAS_NOT_YET);

        System.out.println("查询正在进行的全部众筹:" + crowdfundingProductsList);

        //遍历全部众筹
        for (CrowdfundingProducts crowdfundingProducts : crowdfundingProductsList) {

            System.out.println("开始众筹的判断:" + crowdfundingProducts);

            Long startTime = DateUtil.parseDateString(crowdfundingProducts.getStartDate(), "yyyy-MM-dd HH:mm:ss");
            Long endTime = DateUtil.parseDateString(crowdfundingProducts.getEndDate(), "yyyy-MM-dd HH:mm:ss");
            Long now = DateUtil.parseDateString(DateUtil.parseDateLong(), "yyyy-MM-dd HH:mm:ss");

            System.out.println("开始时间:" + startTime + " || 现在时间:" + now + " || 结束时间:" + endTime);

            if (startTime < now && now < endTime) {//在设置的时间范围内
                if (crowdfundingProducts.getTotalAmount().compareTo(crowdfundingProducts.getTargetAmount()) >= 0) {//已筹集金额大于等于设置金额

                    System.out.println("在时间范围和设置金额已达到");

                    //改变该众筹的状态 FINISH 已完成
                    crowdfundingProducts.setCroedState("FINISH");
                    crowdfundingProductsService.updateById(crowdfundingProducts);


                    CrowdLog crowdLog = new CrowdLog();
                    crowdLog.setLogUser("系统自动");
                    crowdLog.setLogTime(DateUtil.parseDateLong());
                    crowdLog.setLogContnet("众筹完成");
                    crowdLog.setCrowdId(crowdfundingProducts.getId());

                    crowdLogService.save(crowdLog);
                    //众筹ES下架

                    System.out.println("众筹完成，下架es");

                    CrowdEsModel crowdEsModel = new CrowdEsModel();
                    crowdEsModel.setId(crowdfundingProducts.getId());

                    elasticsearchOperations.delete(crowdEsModel);

                    System.out.println("下架完成");

                    //查询该众筹商品相关联的所有用户
                    List<CrowdUserRele> crowd = crowdUserReleService.list(new QueryWrapper<CrowdUserRele>().eq("crowd", crowdfundingProducts.getId()));
                    //遍历所有的用户 下单

                    System.out.println("开始下单，发货");

                    for (CrowdUserRele crowdUserRele : crowd) {
                        CrowdOrder crowdOrder = crowdOrderService.getOne(new QueryWrapper<CrowdOrder>().eq("crowd_id", crowdUserRele.getCrowd()).eq("crowd_user_id", crowdUserRele.getUserId()));
                        if (!crowdOrder.getCrowdOrderState().equals("PAID"))
                            throw new LXLGException(CrowdException.CROWD_ORDER_UNPAID);
                        crowdOrder.setCrowdOrderState("SHIPPED");
                        crowdOrder.setCrowdSuccessTime(DateUtil.parseDateLong());
                        crowdOrderService.updateById(crowdOrder);

                        CrowdOrderLog crowdOrderLog = new CrowdOrderLog();
                        crowdOrderLog.setCrowdLogTime(DateUtil.parseDateLong());
                        crowdOrderLog.setCrowdUserId(crowdUserRele.getUserId());
                        crowdOrderLog.setCrowdOrderId(crowdOrder.getCrowdOrderId());
                        crowdOrderLog.setCrowdOrderNum(crowdOrder.getCrowdOrderNum());
                        crowdOrderLog.setCrowdOrderContent("众筹完成");
                        crowdOrderLogService.save(crowdOrderLog);
                    }

                    System.out.println("发货结束");

                } else {
                    // id搜索ES
                    // 同步数据库数据到ES （以筹集金额 参与人数）

                    System.out.println("在时间范围内但未达到设置金额，同步es数据");

                    UPdateCrowdForm uPdateCrowdForm = new UPdateCrowdForm();
                    uPdateCrowdForm.setId(crowdfundingProducts.getId());
                    uPdateCrowdForm.setTotalAmount(crowdfundingProducts.getTotalAmount());
                    uPdateCrowdForm.setUserCount(crowdfundingProducts.getUserCount());

                    crowdfundingProductsService.updateByCrowdId(uPdateCrowdForm);

                    System.out.println("同步结束");
                }
            } else { //超出时间范围

                System.out.println("超出时间范围");

                //改变该众筹的状态 CANCEL 已取消
                crowdfundingProducts.setStartDate("CANCEL");
                crowdfundingProductsService.updateById(crowdfundingProducts);

                CrowdLog crowdLog = new CrowdLog();
                crowdLog.setLogUser("系统自动");
                crowdLog.setLogTime(DateUtil.parseDateLong());
                crowdLog.setLogContnet("众筹取消");
                crowdLog.setCrowdId(crowdfundingProducts.getId());

                crowdLogService.save(crowdLog);
                // 众筹下ES架

                System.out.println("下架es");

                CrowdEsModel crowdEsModel = new CrowdEsModel();
                crowdEsModel.setId(crowdfundingProducts.getId());

                elasticsearchOperations.delete(crowdEsModel);

                System.out.println("下架结束");

                // 退款
                //查询该众筹商品相关联的所有用户
                System.out.println("查询该众筹商品相关联的所有用户");

                List<CrowdUserRele> crowd = crowdUserReleService.list(new QueryWrapper<CrowdUserRele>().eq("crowd", crowdfundingProducts.getId()));

                System.out.println("开始插入退款数据");

                //遍历所有的用户 下单
                for (CrowdUserRele crowdUserRele : crowd) {
                    CrowdOrder crowdOrder = crowdOrderService.getOne(new QueryWrapper<CrowdOrder>().eq("crowd_id", crowdUserRele.getCrowd()).eq("crowd_user_id", crowdUserRele.getUserId()));
                    if (crowdOrder.getCrowdOrderState().equals("PAID")) {
                        CrowdRefundsMoneyParam crowdRefundsMoneyParam = new CrowdRefundsMoneyParam();
                        crowdRefundsMoneyParam.setOrderId(-1);
                        crowdRefundsMoneyParam.setOrderNum("众筹退款");
                        crowdRefundsMoneyParam.setRefundResongId(-1);
                        crowdRefundsMoneyParam.setRefundOtherReson("众筹退款");

                        //根据众筹id查询众筹
                        CrowdfundingProducts byId = crowdfundingProductsService.getById(crowdUserRele.getCrowd());
                        //根据商品id 查询spu
                        SpuResultInfo data = productQueryClient.getSpuInfoBySpuId(byId.getProductId(), -1).getData();

                        crowdRefundsMoneyParam.setBackMoney(data.getMinPrice());
                        crowdRefundsMoneyParam.setRefundTradeNo("ZC退款" + snowflake.nextId());
                        crowdRefundsMoneyParam.setRefundRemark("众筹退款");
                        crowdRefundsMoneyParam.setRefundTime(DateUtil.parseDateLong());
                        crowdRefundsMoneyParam.setShopRejectReason("众筹退款");
                        crowdRefundsMoneyParam.setRefundStatus(1);
                        crowdRefundsMoneyParam.setCreateTime(DateUtil.parseDateLong());
                        crowdRefundsMoneyParam.setBackScore(0);
                        crowdRefundsMoneyParam.setUserId(crowdUserRele.getUserId());
                        crowdRefundsMoneyParam.setUserNum(crowdUserRele.getCrowdReceiverUser());
                        crowdRefundsMoneyParam.setProductId(crowdfundingProducts.getProductId() + "");
                        crowdRefundsMoneyParam.setRefundresonId(-1);
                        crowdRefundsMoneyParam.setRemarks("众筹退款");

                        refundsApplyManageClient.crowdRefundsMoney(crowdRefundsMoneyParam);

                    }

                }
                System.out.println("退款结束");
            }
            System.out.println("众筹判断结束");
        }
        System.out.println("定时任务执行结束");
    }
}
